﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using MICZ.CodeBuilder.Commons.DataEnum;
using MICZ.CodeBuilder.Commons.ConfigExtensions;
using MICZ.CodeBuilder.ViewModels;
using MICZ.CodeBuilder.IRepository.SqlSugar;
using MICZ.CodeBuilder.IService;
using MICZ.CodeBuilder.Commons.ResponseResult;
using MICZ.CodeBuilder.Commons.Comn;
using MICZ.CodeBuilder.Commons.ServerTypeToModelType;

namespace MICZ.CodeBuilder.ManageApi.Controllers
{
    /// <summary>
    /// 代码生成
    /// </summary>
    public class BuilderController : BaseController
    {
        ISqlSugarRepository SqlSugarRepository;
        IProjectService projectService;
        public BuilderController(ISqlSugarRepository _SqlSugarRepository, IProjectService _projectService)
        {
            SqlSugarRepository = _SqlSugarRepository;
            projectService = _projectService;
        }

        /// <summary>
        /// 修改Json配置文件里面的命名空间参数
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public async Task<IActionResult> NamespaceEdit(string text)
        {
            if (string.IsNullOrWhiteSpace(text))
                return Content(ResponseResult.toJsonString(ResponseResult.Error(ReturnErrorCode.ParameterEmptyCode, ReturnErrorCode.ParameterEmpty)));
            await Task.Run(() =>
            {
                List<string> vs = text.Split(".").ToList();
                foreach (var item in vs.Where(a => string.IsNullOrWhiteSpace(a)))
                {
                    vs.Remove(item);
                }
                text = string.Join(".", vs);
                ConfigExtensions.Write("namespace", text);
            });
            return Content(ResponseResult.toJsonString(ResponseResult.Success()));
        }

        /// <summary>
        /// 读取Json配置文件里面的命名空间参数
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public async Task<IActionResult> Namespace()
        {
            string Result = "";
            await Task.Run(() =>
            {
                Result = ConfigExtensions.Read<String>("namespace");
            });
            return Content(ResponseResult.toJsonString(ResponseResult.Success(Result)));
        }

        /// <summary>
        /// 模板生成输出
        /// </summary>
        /// <param name="Type">类型</param>
        /// <param name="Namespace">命名空间</param>
        /// <param name="TableName">表名</param>
        /// <param name="Description">表注释</param>
        /// <returns></returns>
        [EnableCors]
        //[ServiceFilter(typeof(LoginFilterAttribute))]
        public async Task<IActionResult> Index(BuliderDataEnum.DataEnum Type, string Namespace, string TableName, string Description = "")
        {
            string Result = "";
            //获取所有表
            //var asd = SqlSugarRepository.Db.DbMaintenance.GetTableInfoList(false);
            //SqlSugarRepository.Db.DbMaintenance.GetTableInfoList(false).Where(a=>a.Name== "UserInfo")//过滤选择某个表
            //获取某个表里面的所有字段
            //var b = SqlSugarRepository.Db.DbMaintenance.GetColumnInfosByTableName("UserInfo", false);
            if (string.IsNullOrWhiteSpace(Namespace))
                Namespace = ConfigExtensions.Read<string>("namespace");
            SqlSugarRepository.Db.Open();
            if (string.IsNullOrWhiteSpace(Description) && !string.IsNullOrWhiteSpace(TableName))
            { 
               var dbTableInfos=SqlSugarRepository.Db.DbMaintenance.GetTableInfoList(false).Where(a=>a.Name.Trim().ToUpper()==TableName.Trim().ToUpper()).ToList();
                if (dbTableInfos.Count > 0)
                    Description = dbTableInfos[0].Description;
            }
            #region 查询某个表的所以列
            List<BuilderColumnViewModel> GetListColumns()
            {
                var lsColumns = SqlSugarRepository.Db.DbMaintenance.GetColumnInfosByTableName(TableName, false);
                List<BuilderColumnViewModel> lsobj = new List<BuilderColumnViewModel>();
                foreach (var item in lsColumns)
                {
                    BuilderColumnViewModel _obj = new BuilderColumnViewModel()
                    {
                        Namespace = Namespace,
                        TableName = TableName,
                        ColumnIsPrimarykey=item.IsPrimarykey,
                        ColumnIsIdentity = item.IsIdentity,
                        ColumnName = item.DbColumnName,
                        Type = ServerTypeToModelType.ServerConverModel(item.DataType),
                        Description = item.ColumnDescription
                    };
                    lsobj.Add(_obj);
                }
                return lsobj;
            }
            #endregion
            //Service,AppService层
            if (Type == BuliderDataEnum.DataEnum.IService || Type == BuliderDataEnum.DataEnum.Service || Type == BuliderDataEnum.DataEnum.IApplocation || Type == BuliderDataEnum.DataEnum.Applocation)
            {
                if (string.IsNullOrWhiteSpace(TableName))
                {
                    JsonDataModel.Status = 0;
                    JsonDataModel.Msg = "参数不能为空";
                    return new JsonResult(JsonDataModel);
                }
                //db.DbFirst.CreateClassFile("D:\\Demo", "Models");
                //Result = Engine.Razor.RunCompile(template, "MICZTemplate", null, new { TableName = item.Name });
                //Template =await System.IO.File.ReadAllTextAsync(Path.Combine(CodeTemplate, "IService.cs"));
                //Result = Engine.Razor.RunCompile(Template, TemplateName, null, new { TableName = TableName, Description = Description });
                //string _TemplateName = Type.ToString().Replace("IApplocation", "IAppService").Replace("Applocation", "AppService");
                string _TemplateName = Type.ToString().Replace("Applocation", "AppService");
                Result = await projectService.TemplateCode(_TemplateName, new BuilderTableViewModel { Namespace = Namespace, TableName = TableName, Description = Description, Columns = GetListColumns() });
            }
            else if (Type==BuliderDataEnum.DataEnum.Controller)//Controller
            {
                if (string.IsNullOrWhiteSpace(TableName))
                {
                    JsonDataModel.Status = 0;
                    JsonDataModel.Msg = "参数不能为空";
                    return new JsonResult(JsonDataModel);
                }
                Result = await projectService.ControllerTemplateCode(Type.ToString(), new BuilderTableViewModel { Namespace = Namespace, TableName = TableName, Description = Description, Columns = GetListColumns() });
            } 
            else if (Type == BuliderDataEnum.DataEnum.IRepository || Type == BuliderDataEnum.DataEnum.Repository)//Repository层
            {
                List<BuilderTableViewModel> RepositoryLsobj = new List<BuilderTableViewModel>();
                foreach (var item in SqlSugarRepository.Db.DbMaintenance.GetTableInfoList())
                {
                    RepositoryLsobj.Add(new BuilderTableViewModel { Namespace = Namespace, TableName = item.Name, Description = item.Description, Columns = null });
                }
                Result = await projectService.RepositoryTemplateCode(Type.ToString(), RepositoryLsobj);
            }
            else if (Type == BuliderDataEnum.DataEnum.Model || Type == BuliderDataEnum.DataEnum.ViewModel)//Model层
            {
                if (string.IsNullOrWhiteSpace(TableName))
                {
                    JsonDataModel.Status = 0;
                    JsonDataModel.Msg = "参数不能为空";
                    return new JsonResult(JsonDataModel);
                }
                //projectService.ModelCreate(ConfigExtensions.GetConnectionString("namespace").ToString(),1);
                List<BuilderColumnViewModel> _Model = GetListColumns();
                //foreach (var item in _Model)
                //{
                //    item.Type = ServerTypeToModelType.ServerConverModel(item.Type);
                //}
                Result = await projectService.TemplateModel(Namespace, _Model, Type == BuliderDataEnum.DataEnum.Model ? 1 : 2);
            }
            else if (Type == BuliderDataEnum.DataEnum.Register||Type == BuliderDataEnum.DataEnum.AutoMapper) {
                List<BuilderTableViewModel> RepositoryLsobj = new List<BuilderTableViewModel>();
                foreach (var item in SqlSugarRepository.Db.DbMaintenance.GetTableInfoList())
                {
                    RepositoryLsobj.Add(new BuilderTableViewModel { Namespace = Namespace, TableName = item.Name, Description = item.Description, Columns = null });
                }
                Result = await projectService.RepositoryTemplateCode(Type.ToString(), RepositoryLsobj);
            }
            SqlSugarRepository.Db.Close();
            dynamic obj = new MICZ.CodeBuilder.Commons.DynamicExtensions.DynamicObjectHelper();
            obj.set("Obj", Result);
            //return Content(Result);
            JsonDataModel.Status = 1;
            JsonDataModel.Data = obj;
            return new JsonResult(JsonDataModel);
        }


        /// <summary>
        /// 项目创建(.csproj)
        /// </summary>
        /// <param name="Type">类型</param>
        /// <param name="Namespace">命名空间</param>
        /// <returns></returns>
        [EnableCors]
        //[ServiceFilter(typeof(LoginFilterAttribute))]
        public async Task<IActionResult> Project(BuliderDataEnum.DataEnum Type, string Namespace)
        {
            if (string.IsNullOrWhiteSpace(Namespace))
                Namespace = ConfigExtensions.Read<string>("namespace");
            //Namespace = ConfigExtensions.GetConnectionString("namespace").ToString();
            SqlSugarRepository.Db.Open();
            var lsTables = SqlSugarRepository.Db.DbMaintenance.GetTableInfoList(false);
            #region 查询某个表的所以列
            List<BuilderColumnViewModel> GetListColumns(string _TableName)
            {
                var lsColumns = SqlSugarRepository.Db.DbMaintenance.GetColumnInfosByTableName(_TableName, false);
                List<BuilderColumnViewModel> lsobj = new List<BuilderColumnViewModel>();
                foreach (var item in lsColumns)
                {
                    BuilderColumnViewModel _obj = new BuilderColumnViewModel()
                    {
                        Namespace = Namespace,
                        TableName = _TableName,
                        ColumnIsPrimarykey=item.IsPrimarykey,
                        ColumnIsIdentity = item.IsIdentity,
                        ColumnName = item.DbColumnName,
                        Type = ServerTypeToModelType.ServerConverModel(item.DataType),
                        Description = item.ColumnDescription
                    };
                    lsobj.Add(_obj);
                }
                return lsobj;
            }
            #endregion
            //Service,AppService层
            if (Type == BuliderDataEnum.DataEnum.IService || Type == BuliderDataEnum.DataEnum.Service || Type == BuliderDataEnum.DataEnum.IApplocation || Type == BuliderDataEnum.DataEnum.Applocation)
            {
                //string _TemplateName = Type.ToString().Replace("IApplocation", "IAppService").Replace("Applocation", "AppService");
                string _TemplateName = Type.ToString().Replace("Applocation", "AppService");
                projectService.CreateProject(Namespace + "." + _TemplateName);
                foreach (var item in lsTables)
                {
                    projectService.TemplateCreate(_TemplateName, new BuilderTableViewModel { Namespace = Namespace, TableName = item.Name, Description = item.Description, Columns = GetListColumns(item.Name) });
                }
            }
            else if (Type == BuliderDataEnum.DataEnum.Controller) //Controller
            {
                projectService.CreateProject(Namespace + "." + Type.ToString());
                foreach (var item in lsTables)
                {
                    projectService.ControllerTemplateCreate(Type.ToString(), new BuilderTableViewModel { Namespace = Namespace, TableName = item.Name, Description = item.Description, Columns = GetListColumns(item.Name) });
                }
            }  
            else if (Type == BuliderDataEnum.DataEnum.IRepository || Type == BuliderDataEnum.DataEnum.Repository) //Repository层
            {
                projectService.CreateProject(Namespace + "." + Type.ToString());
                List<BuilderTableViewModel> RepositoryLsobj = new List<BuilderTableViewModel>();
                foreach (var item in SqlSugarRepository.Db.DbMaintenance.GetTableInfoList())
                {
                    RepositoryLsobj.Add(new BuilderTableViewModel { Namespace = Namespace, TableName = item.Name, Description = item.Description, Columns = null });
                }
                projectService.RepositoryTemplateCreate(Type.ToString(), RepositoryLsobj);
            }
            else if (Type == BuliderDataEnum.DataEnum.Model || Type == BuliderDataEnum.DataEnum.ViewModel)//Model层
            {
                projectService.CreateProject(Namespace + "." + Type.ToString());
                projectService.ModelCreate(Namespace, Type == BuliderDataEnum.DataEnum.Model ? 1 : 2);
            }
            else if (Type == BuliderDataEnum.DataEnum.Register||Type==BuliderDataEnum.DataEnum.AutoMapper)
            {
                projectService.CreateProject(Namespace + "." + Type.ToString());
                List<BuilderTableViewModel> RepositoryLsobj = new List<BuilderTableViewModel>();
                foreach (var item in SqlSugarRepository.Db.DbMaintenance.GetTableInfoList())
                {
                    RepositoryLsobj.Add(new BuilderTableViewModel { Namespace = Namespace, TableName = item.Name, Description = item.Description, Columns = null });
                }
                projectService.RepositoryTemplateCreate(Type.ToString(), RepositoryLsobj);
            }
            SqlSugarRepository.Db.Close();
            //return Content(Result);
            JsonDataModel.Status = 1;
            JsonDataModel.Msg = Namespace + "." + Type.ToString() + "项目生成成功！";
            return new JsonResult(JsonDataModel);
        }

    }
}
